<template>
  <div class="lazy-container">
    <img ref="imgRef" class="lazy-image" :src="currentSrc" :alt="alt" @load="handleLoad" />
  </div>
</template>

<script>
import { ref, onMounted, inject } from "vue";

export default {
  props: {
    url: {
      type: String,
      default: ""
    },
    alt: {
      type: String,
      default: ""
    }
  },

  setup(props, { emit }) {
    const imgRef = ref(null);
    const currentSrc = ref('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"></svg>');
    const refreshLayout = inject('refreshLayout');

    const loadImage = () => {
      if (!props.url) return;

      const img = new Image();
      img.onload = () => {
        currentSrc.value = props.url;
        emit('loaded');
        // 延迟刷新布局以确保图片尺寸已应用
        setTimeout(refreshLayout, 100);
      };
      img.onerror = () => emit('error');
      img.src = props.url;
    };

    const handleLoad = () => {
      emit('loaded');
    };

    onMounted(() => {
      setTimeout(loadImage, 300);
    });

    return {
      imgRef,
      currentSrc,
      handleLoad
    };
  }
};
</script>

<style scoped>
.lazy-container {
  position: relative;
  width: 100%;
}

.lazy-image {
  display: block;
  width: 100%;
  height: auto;
  opacity: 1;
  transition: opacity 0.3s ease;
}
</style>